import axios from 'axios'
import auth from '@/utils/auth'
import storage from '@/utils/storage'
import { refreshToken as refreshTokenApi } from '@/api/login'
import permissionMiddleware from '@/utils/permissionMiddleware'

let isRefreshing = false;
let refreshSubscribers = [];
export const baseURL = "https://api-admin.monkeymeerkat.cn/api"
// export const baseURL = "http://localhost:5002/api"
function onRefreshed(newToken) {
  refreshSubscribers.forEach(cb => cb(newToken));
  refreshSubscribers = [];
}

function addRefreshSubscriber(cb) {
  refreshSubscribers.push(cb);
}

 const service = axios.create({
    baseURL: baseURL, // 前端请求直接走后端域名
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 添加token到请求头
        const tokenObj = storage.get('token')
        if (tokenObj && tokenObj.accessToken) {
            config.headers.Authorization = `Bearer ${tokenObj.accessToken}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 直接返回data
        return response.data
    },
    async error => {
        const originalRequest = error.config;
        
        // 处理403权限不足错误
        if (error.response && error.response.status === 403) {
            // 使用全局权限验证中间件处理403错误
            permissionMiddleware.handlePermissionDenied(error, { showMessage: true });
            return Promise.reject(error);
        }
        
        // 处理token过期
        if (error.response && error.response.status === 401) {
            const tokenObj = storage.get('token');
            const refresh_token = tokenObj && tokenObj.refreshToken;
            const rememberFlag = localStorage.getItem('rememberFlag');
            
            // 如果没有refreshToken，直接登出
            if (!refresh_token) {
                // 只有本地有token才弹窗，否则静默跳转
                const tokenObj = storage.get('token');
                auth.logout(!!(tokenObj && tokenObj.accessToken));
                return Promise.reject(error);
            }
            
            // 如果用户勾选了记住登录，尝试自动刷新token
            if (rememberFlag === 'true') {
                // 防止多次并发刷新
                if (!isRefreshing) {
                    isRefreshing = true;
                    try {
                        const res = await refreshTokenApi({ refreshToken: refresh_token });
                        if (res && res.accessToken) {
                            // 解析exp生成expiresAt
                            let expiresAt;
                            try {
                                if (res.accessToken) {
                                    const tokenParts = res.accessToken.split('.');
                                    if (tokenParts.length >= 2) {
                                        const base64Url = tokenParts[1];
                                        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                                        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
                                            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                                        }).join(''));
                                        const jwtPayload = JSON.parse(jsonPayload);
                                        if (jwtPayload.exp) {
                                            expiresAt = new Date(jwtPayload.exp * 1000).toISOString();
                                        }
                                    }
                                }
                            } catch (parseError) {
                                console.error('解析JWT失败:', parseError)
                            }
                            const newTokenObj = { ...tokenObj, ...res, expiresAt };
                            storage.set('token', newTokenObj);
                            localStorage.setItem('accessToken', res.accessToken);
                            localStorage.setItem('refreshToken', res.refreshToken);
                            isRefreshing = false;
                            onRefreshed(newTokenObj.accessToken);
                            
                            // 显示自动刷新成功消息
                            const { ElMessage } = await import('element-plus');
                            ElMessage.success('Token已自动刷新，继续使用中...');
                            
                            // 重试原请求
                            originalRequest.headers['Authorization'] = `Bearer ${newTokenObj.accessToken}`;
                            return service(originalRequest);
                        } else {
                            auth.logout(false); // 不显示提示信息，避免重复提示
                            return Promise.reject(error);
                        }
                    } catch (refreshError) {
                        console.error('刷新token失败:', refreshError)
                        auth.logout(false); // 不显示提示信息，避免重复提示
                    } finally {
                        isRefreshing = false;
                    }
                } else {
                    // 正在刷新，挂起请求
                    return new Promise((resolve) => {
                        addRefreshSubscriber((newAccessToken) => {
                            originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`;
                            resolve(service(originalRequest));
                        });
                    });
                }
            } else {
                // 用户没有勾选记住登录，直接登出
                auth.logout(false); // 不显示提示信息，避免重复提示
                return Promise.reject(error);
            }
        }
        return Promise.reject(error)
    }
)

export default service
